<template>
  <div class="index-page">
    <!-- 搜索框模块 -->
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-form :model="queryParams" label-width="100px" v-show="showSearch">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="评估机构" id="index">
                  <el-input
                    placeholder="请输入评估机构名称"
                    clearable
                    v-model="queryParams.assessOrganizationName"
                  >
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item label="状态">
                  <el-select
                    clearable
                    v-model="queryParams.assessStatus"
                    placeholder="请选择评估状态"
                  >
                    <el-option
                      v-for="item in assess_status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="14">
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <el-row style="margin-bottom: 10px">
        <el-col :span="5">
          <el-button plain type="primary" icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>

        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
        style="width: 100%"
        max-height="500"
      >
        <el-table-column
          prop="name"
          width="200"
          label="评估机构"
        ></el-table-column>

        <el-table-column
          prop="contact"
          width="200"
          label="联系人"
        ></el-table-column>

        <el-table-column
          prop="phone"
          width="200"
          label="联系电话"
        ></el-table-column>

        <el-table-column label="联系地址">
          <template v-slot:default="scope">
            <span>{{
              scope.row.provinceName + scope.row.cityName + scope.row.address
            }}</span>
          </template>
        </el-table-column>

        <el-table-column width="100" label="状态">
          <template v-slot:default="scope">
            <el-tag :type="scope.row.status === '0' ? '' : 'danger'">
              <span>
                {{
                  assess_status.find((item) => item.value == scope.row.status)
                    ? assess_status.find(
                        (item) => item.value == scope.row.status
                      ).label
                    : ""
                }}</span
              >
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250">
          <template v-slot:default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleAssessPeople(scope.row)"
              >评估人员</el-button
            >
            <el-button type="danger" link @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 全局分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      ></pagination>
    </el-card>

    <!-- 新增编辑弹框 -->
    <el-dialog
      v-model="dialogShow"
      :title="dialogTitle + '评估机构'"
      width="50%"
      v-if="dialogShow"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form label-width="120" :model="form" ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="评估机构名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入评估机构名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input
                v-model="form.contact"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="9">
            <el-form-item label="联系地址" prop="provinceId">
              <!-- {{regionData}} -->
              <el-select
                value-key="areaCode"
                v-model="form.provinceId"
                placeholder="请选择省"
                @change="changeProvince"
                filterable
              >
                <el-option
                  v-for="dict in regionList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item prop="cityId" id="citycontent">
              <el-select
                value-key="areaCode"
                v-model="form.cityId"
                placeholder="请选择市"
                @change="changeCity"
                filterable
              >
                <el-option
                  v-for="dict in CityList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item prop="countyId" id="areacontent">
              <el-select
                value-key="areaCode"
                v-model="form.countyId"
                placeholder="请选择区/县"
                @change="changeCounty"
                filterable
              >
                <el-option
                  v-for="dict in countyList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="item in assess_status" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input
                v-model="form.notes"
                type="textarea"
                show-word-limit
                maxlength="500"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <span>
          <el-button type="primary" @click="submitFormDebounceHandler"
            >确定</el-button
          >
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getProvinceData } from "../../../api/supplierManagement/index.js";
import {
  getAssessOrganizationData,
  addNewAssessOrganizationData,
  editAssessOrganizationData,
  deleteAssessOrganizationData,
} from "../../../api/assessOrganization/index";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { region } from "@/api/record/api";
const router = useRouter();
const { proxy } = getCurrentInstance();
import { debounce } from "@/utils/debounce.js";

// 字典-评估状态类型
const { assess_status } = proxy.useDict("assess_status");
const regionList = ref([]);
const CityList = ref([]);
const countyList = ref([]);
const data = reactive({
  form: {
    status: "0",
  },

  queryParams: {
    page: 1,
    limit: 10,
    assessOrganizationName: undefined,
    assessStatus: undefined,
  },
  rules: {
    name: [
      { required: true, message: "机构名称不能为空", trigger: "blur" },
      {
        required: true,
        min: 1,
        max: 50,
        message: "机构名称不超过50个字符",
        trigger: "blur",
      },
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      {
        required: true,
        min: 11,
        max: 11,
        message: "联系电话长度为11位数字",
        trigger: "blur",
      },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    contact: [
      { required: true, message: "联系人不能为空", trigger: "blur" },
      {
        required: true,
        min: 1,
        max: 10,
        message: "联系人不超过10个字符",
        trigger: "blur",
      },
    ],
    provinceId: [
      { required: true, message: "联系地址不能为空", trigger: "change" },
    ],
    // cityId: [{ required: true, message: "市不能为空", trigger: "change" }],
    // countyId: [{ required: true, message: "区不能为空", trigger: "change" }],
    address: [
      { required: true, message: "详细地址不能为空", trigger: "blur" },
      {
        required: true,
        min: 1,
        max: 50,
        message: "详细地址不超过50个字符",
        trigger: "blur",
      },
    ],
    notes: [
      { required: false, message: "请输入备注", trigger: "blur" },
      {
        required: false,
        min: 1,
        max: 500,
        message: "备注不超过500个字符",
        trigger: "blur",
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

// 显示弹框
const dialogShow = ref(false);
// 弹框标题
const dialogTitle = ref("新增");
const showSearch = ref(true);
const loading = ref(true);
// 搜索表单
// 分页
const total = ref(0);
// 表格
const tableData = ref([]);

// 拿表格数据
const getList = () => {
  loading.value = true;
  // 整理查询参数
  getAssessOrganizationData(queryParams.value)
    .then((res) => {
      tableData.value = res.page.list;
      loading.value = false;
      total.value = res.page.totalCount;
    })
    .catch((error) => {});
};

// 点击搜索按钮
const handleQuery = () => {
  getList();
};

// 点击重置按钮
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    assessOrganizationName: undefined,
    assessStatus: undefined,
  };
  getList();
};
// 点击新增按钮
const handleAdd = () => {
  dialogShow.value = true;
  dialogTitle.value = "新增";
};

const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
  proxy.$refs["ruleFormRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        editAssessOrganizationData(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          dialogShow.value = false;
          reset();
          getList();
        });
      } else {
        addNewAssessOrganizationData(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          dialogShow.value = false;
          reset();
          getList();
        });
      }
    }
  });
}
// 关闭弹框
const closeDialog = () => {
  dialogShow.value = false;
  reset();
};
function reset() {
  form.value = {
    id: null,
    name: undefined,
    contact: undefined,
    phone: undefined,
    provinceId: null,
    cityId: null,
    countyId: null,
    provinceName: null,
    cityName: null,
    countyName: null,
    address: null,
    status: "0",
    notes: null,
  };
  proxy.resetForm("ruleFormRef");
  CityList.value = [];
  countyList.value = [];
}

// 点击修改
async function handleEdit(data) {
  form.value = data;
  const data1 = await region(data.provinceId);
  const data2 = await region(data.cityId);
  CityList.value = data1.data;
  countyList.value = data2.data;
  dialogShow.value = true;
  dialogTitle.value = "编辑";
}

// 点击删除
const handleDelete = (data) => {
  ElMessageBox.confirm(`是否确定删除${data.name}`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAssessOrganizationData([data.id])
        .then((res) => {
          getList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        })
        .catch((error) => {});
    })
    .catch((error) => {
      ElMessage({
        type: "warning",
        message: "取消删除",
      });
    });
};

// 写方法处理状态

function getregion() {
  region(0).then((res) => {
    console.log(res);
    regionList.value = res.data;
  });
}

function changeProvince(val) {
  form.value.provinceName = regionList.value.find(
    (item) => item.areaCode == val
  )?.name;
  CityList.value = [];
  form.value.cityId = "";
  form.value.countyId = "";
  countyList.value = [];
  region(val).then((res) => {
    CityList.value = res.data;
  });
}
function changeCity(val) {
  form.value.cityName = CityList.value.find(
    (item) => item.areaCode == val
  )?.name;
  form.value.countyId = "";
  countyList.value = [];
  region(val).then((res) => {
    countyList.value = res.data;
  });
}
function changeCounty(val) {
  form.value.countyName = countyList.value.find(
    (item) => item.areaCode == val
  )?.name;
}
// 点击评估人员
const handleAssessPeople = (data) => {
  router.push({
    name: "people",
    params: {
      id: data.id,
      name: data.name,
    },
  });
};

getList();
getregion();
</script>

<style lang="scss" scoped>
.index-page {
  padding: 20px;
}

:deep(.el-form-item[id="index"] .el-form-item__label) {
  // border:1px solid orange;
  width: 70px !important;
}

// 改市的下拉框的长度
:deep(.el-form-item[id="citycontent"] .el-form-item__content) {
  margin-left: 3px !important;
}

// 改区的下拉框的长度
:deep(.el-form-item[id="areacontent"] .el-form-item__content) {
  margin-left: 3px !important;
}
</style>
